package com.gopay.scheduler.shedulerx.alarm;

import com.gopay.common.constants.cust.SMSType;
import com.gopay.common.constants.scheduler.SchedulerConstants;
import com.gopay.cron.web.util.PropertiesUtil;
import com.gopay.scheduler.common.SendMsg;
import com.gopay.scheduler.shedulerx.SchedulerOperateFactory;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * @author 19371
 */
public class SimpleAlarm {

    private final static Logger LOGGER = LoggerFactory.getLogger(SimpleAlarm.class);

    private static SimpleAlarm alarmer = new SimpleAlarm();

    private SimpleAlarm() {
    }

    public static SimpleAlarm getSingle(){
        return alarmer;
    }

    public void alarm(AlarmEvent alarmEvent){
        String msg = "";
        boolean alarm = false;
        SchedulerOperateFactory operateFactory = SchedulerOperateFactory.getFactory();
        HashMap<String, Integer> alarmCountMapping = operateFactory.getAlarmCountMapping();
        Integer alarmCount = alarmCountMapping.get(alarmEvent.getJobName());
        Integer failCount = alarmCount == null ? 0 : alarmCount;
        if(SchedulerConstants.SCHEDULER_ALARM_HIGH.equals(alarmEvent.getAlarmLevel())){
            msg = String.format("项目:{%s},作业域:{%s},JOB={%s:%s}在{%s}发生异常，报警等级为高级;发生异常的次数为{%s}，请及时处理",alarmEvent.getAppName()
            ,alarmEvent.getRegion(),alarmEvent.getJobName(),alarmEvent.getDecription(),alarmEvent.getEventTime(),++failCount);
            alarm = true;
        }else if(SchedulerConstants.SCHEDULER_ALARM_MID.equals(alarmEvent.getAlarmLevel())) {
            if ((++failCount) % SchedulerConstants.ALAEM_FAIL_COUNT == 0) {
                msg = String.format("项目:{%s},作业域:{%s},JOB={%s:%s}在{%s}发生异常，报警等级为中级;发生异常的次数为{%s}，请及时处理",alarmEvent.getAppName()
                        ,alarmEvent.getRegion(),alarmEvent.getJobName(),alarmEvent.getDecription(),alarmEvent.getEventTime(),failCount);
                alarm = true;
            }
        }
        alarmCountMapping.put(alarmEvent.getJobName(),failCount);
        if (alarm){
            alarm(msg);
        }
    }

    private void alarm(String msg) {
        try {
            LOGGER.info(String.format("<--------发送警报,警报内容{%s}----->",msg));
            sendSMSAlarm(msg);
        }catch (Exception e){
            LOGGER.error(String.format("<--------发送警报失败,警报内容{%s}----->",msg),e);

        }
    }

    private String mobile(){
        return PropertiesUtil.getValue("jobCron.recvMobile");
    }

    private void sendSMSAlarm(String content) {
        RequestVO req = new RequestVO();
        req.setAppId(SMSAppId._90000.value);
        req.setMobile(mobile());
        req.setContent(content);
        GopaySMSHttpClient.getInstance().createVerificationCode(req);
    }
}
